package org.spring.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//-------------------------------------------------------------------------
// 原始JDBC编程的步骤
//-------------------------------------------------------------------------
//* 1- 注册驱动
//*      告知JVM使用的是哪一个数据库的驱动
//* 2- 获得链接
//*      使用JDBC中的类，完成对数据库的链接
//* 3- 获得语句执行平台
//*      通过连接对象获取对sql语句的执行对象
//* 4- 执行sql语句
//*      使用执行对象，想数据库执行sql 语句
//*      获取到数据库的执行后的结果
//* 5- 处理结果
//* 6- 释放资源
//*      调用一堆的close();
//---------------------
public class TraditionalStyle {

	public static void main(String[] args) {
		
		// 1.通过直接赋值方式配置 或者存放在属性文件中
		String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
		String user = "learn_app";
		String password = "xpar";
		String driverClass = "oracle.jdbc.driver.OracleDriver";
		
		try {
			//usePreparedStatement(url, user, password, driverClass);
			userStatement(url, user, password, driverClass);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void usePreparedStatement(String url, String user, String password, String driverClass) throws ClassNotFoundException, SQLException {
		// 2.连接操作
		Class.forName(driverClass); // 注册驱动
		Connection connection = DriverManager.getConnection(url, user, password);

		// 3.CRUD操作
		String sql = "select * from USER_TABLES";

		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		ResultSet resultSet = preparedStatement.executeQuery();

		// 4.处理结果
		while (resultSet.next()) {
			System.out.println("TABLE_NAME: " + resultSet.getString("TABLE_NAME"));
		}

		// 5.关闭资源
		preparedStatement.close();
		connection.close();
	}
	
	public static void userStatement(String url, String user, String password, String driverClass) throws ClassNotFoundException, SQLException {
		// 2.连接操作
		Class.forName(driverClass); // 注册驱动
		Connection connection = DriverManager.getConnection(url, user, password);
		
		// 3.CRUD操作
		String sql = "select * from USER_TABLES";
		
		Statement statement = connection.createStatement();
		ResultSet resultSet = statement.executeQuery(sql);
		
		// 4.处理结果
		while (resultSet.next()) {
			System.out.println("TABLE_NAME: " + resultSet.getString("TABLE_NAME"));
		}

		// 5.关闭资源
		statement.close();
		connection.close();
	}
}
